﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using AssetManagementSystem.Model;

namespace AssetManagementSystem.Utils {
    class SearchUtil {

        public static int NGramSearch(string find, string textToSearch, int n) {
            find = find.ToLower().Replace(" ", "");
            textToSearch = textToSearch.ToLower().Replace(" ", "");
            int matches = 0;

            matches += Regex.Matches(textToSearch, find).Count;

            for (int i = 0; i < find.Length - (n - 1); i++) {
                matches += Regex.Matches(textToSearch, find.Substring(i, n)).Count;
            }

            return matches;
        }

        public static List<Student> FindStudents(List<Student> allStudents, string searchTerm) {
            List<SortObject> sortList = new List<SortObject>();

            foreach (Student student in allStudents) {
                int ngramMatches = NGramSearch(searchTerm, student.ToString(), 3);
                if(ngramMatches > 0){
                    sortList.Add(new SortObject(ngramMatches, student));
                }
            }

            sortList.Sort();

            List<Student> matchedStudents = new List<Student>();
            foreach (SortObject obj in sortList) {
                matchedStudents.Add((Student)obj.TheObject);
            }
            return matchedStudents;
        }


    }
}
